import { useState } from 'react';
import { User } from '../types/User';
import { useUserStore } from '../store/userStore';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  MenuItem,
} from '@mui/material';

interface Props {
  user?: User;
  onClose: () => void;
}

export default function UserForm({ user, onClose }: Props) {
  const { addUser, updateUser } = useUserStore();
  const [form, setForm] = useState<User>(
    user ?? { id: Date.now(), name: '', email: '', role: 'User' }
  );

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    user ? updateUser(form) : addUser(form);
    onClose();
  };

  return (
    <Dialog open onClose={onClose}>
      <DialogTitle>{user ? 'Edit User' : 'Add User'}</DialogTitle>
      <form onSubmit={handleSubmit}>
        <DialogContent>
          <TextField
            margin="dense"
            label="Name"
            fullWidth
            value={form.name}
            onChange={(e) => setForm({ ...form, name: e.target.value })}
          />
          <TextField
            margin="dense"
            label="Email"
            fullWidth
            value={form.email}
            onChange={(e) => setForm({ ...form, email: e.target.value })}
          />
          <TextField
            margin="dense"
            label="Role"
            fullWidth
            select
            value={form.role}
            onChange={(e) =>
              setForm({ ...form, role: e.target.value as User['role'] })
            }
          >
            <MenuItem value="User">User</MenuItem>
            <MenuItem value="Admin">Admin</MenuItem>
          </TextField>
        </DialogContent>
        <DialogActions>
          <Button onClick={onClose}>Cancel</Button>
          <Button type="submit" variant="contained" color="primary">
            {user ? 'Update' : 'Add'}
          </Button>
        </DialogActions>
      </form>
    </Dialog>
  );
}
